import {Component, OnInit} from '@angular/core';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../../config/api';
import {Router} from '@angular/router';
import {PromoteService} from '../promote.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Observable} from 'rxjs/Observable';
import * as moment from 'moment';
import {
  FormBuilder,
  FormGroup,
  FormControl,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [PromoteService]
})

export class AddComponent implements OnInit {
  validateForm: FormGroup;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  goodsModalVisible = false;
  pickType = 'goods';

  goodsData = [];
  activityData = [];
  searchGoodsName: string;
  searchTaskName: string;
  loading = false;
  page = 1;
  pageSize = 5;
  total;
  picked = {type: '', info: {id: ''}};
  checked = {type: '', info: {id: ''}};
  level;
  endDateValidators = false;

  _startDate = null;
  _endDate = null;

  activityGoodsType = 1;
  winnersNumber = 0;
  activityStartDate;
  activityEndDate;
  flag = true;
  categories = [];
  selectedCategory = '';
  firstCategory = null;
  fileList = [];
  picList = [];


  categories1 = [];
  secondCategory = {};

  keywordList = [];
  num = 0;
  short_name_arr = [];
  categoryError = true;
  categoryTouched = false;
  addStatus = false;

  activityTypeOptions = [
    { value: 0, label: '普通活动' },
    // { value: 1, label: '浪花活动' },
    // { value: 2, label: '免费试用' },
    // { value: 3, label: '领券中心' },
    // { value: 4, label: '浪花社区' },
    { value: 5, label: '秒杀活动' }
  ];

  constructor(private fb: FormBuilder,
              private router: Router,
              private promoteService: PromoteService,
              private _message: NzMessageService) {
    this.validateForm = this.fb.group({
      task_name: ['', [Validators.required, Validators.maxLength(40)]],
      type: [1, [Validators.required]],
      point: ['', [Validators.required, Validators.min(1), Validators.max(99999999)], [this.validatorsPoint]],
      max_completion_times: ['', [Validators.required, Validators.min(0), Validators.max(99999999)]],
      activity_type:[0],
      validity_start: ['', [Validators.required]],
      validity_end: ['', [Validators.required]],
      task_content_relation_id: ['', [Validators.required]],
      task_content_type: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    this.getGoodsList();
    this.getCategoryList(1, 0);
    this.getKeywordList();
    this._startDate = new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 00:00:00');
    this._endDate = new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 23:59:59');
    // this.validateForm.controls['validity_start'].setValue(new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 00:00:00'));
    // this.validateForm.controls['validity_end'].setValue(new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 23:59:59'));
  }

  keyDown(e,which) {
    switch (e.code + which) {
      case 'Enter1':
        this.getGoodsList();
        break;
      case "Enter2":
        this.getActivityList();
        break;
    }
  }

  showActivity(e) {
    console.log('controls.value',this.validateForm.controls['activity_type'].value);
  }

  reset(which) {
    if(which === 1) {
      this.searchGoodsName = '';
      this.getGoodsList();
    } else {
      this.searchTaskName = '';
      this.getActivityList()
    }
  }

  validatorsPoint = (control: FormControl, type?): any => {
    const aa = this;
    return Observable.create(function (observer) {
      setTimeout(() => {
        const taskType = type || aa.validateForm.value.type;
        if (taskType === 1) {
          if (control.value < 100) {
            observer.next({error: true, lower: true});
          } else {
            observer.next(null);
          }
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  getCategoryList(level, parent_id) {
    this.promoteService.getCategoryList(level, parent_id).subscribe(res => {
      if (res.code == 2000) {
        this.categories = res.data;
        this.categories.map((e, i) => {
          this.categories1.push({
            value: e.id,
            label: e.category_name
          });
          this.secondCategory[e.category_name] = [];
        });
        // if(Object.prototype.toString.call(this.categories) === '[object Array]') {
        //   this.categories.map((e, i) => {
        //     this.categories1.push({
        //       value: e.id,
        //       label: e.category_name
        //     });
        //     this.secondCategory[e.category_name] = [];
        //   });
        // } else {
        //   for(let key in this.categories) {
        //     this.categories1.push({
        //       value: this.categories[key]['id'],
        //       label: this.categories[key]['category_name']
        //     });
        //     this.secondCategory[this.categories[key]['category_name']] = [];
        //   }
        // }
        this.selectedCategory = this.categories[0];
        this.firstCategory = this.categories[0]['id'];
        this.promoteService.getCategoryList(2, this.categories[0]['id']).subscribe(res => {
          if (res.code == 2000) {
            // this.secondCategory = res.data[0]['id'];
          }
        })
      }
    })
  }

  _startValueChange = () => {
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  }

  _endValueChange = () => {
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  }

  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.validateForm.controls['validity_end'].value) {
      return startValue < now_time;
    }
    if (!(this.pickType === 'goods')) {
      return (startValue.getTime() >= this.activityEndDate.getTime()) || (startValue < this.activityStartDate.getTime())
    } else {
      return (startValue.getTime() >= this.validateForm.controls['validity_end'].value.getTime()) || (startValue <= now_time)
    }
    // console.log(startValue.getTime(), this.validateForm.controls['validity_end'].value.getTime() ,startValue.getTime() >= this.validateForm.controls['validity_end'].value.getTime());
    // return (startValue.getTime() >= this.validateForm.controls['validity_end'].value.getTime()) || (startValue < now_time);
  };


  _disabledEndDate = (endValue) => {

    if (!endValue || !this.validateForm.controls['validity_start'].value) {
      return false;
    }
    if (!(this.pickType === 'goods')) {
      return (endValue.getTime() <= this.validateForm.controls['validity_start'].value.getTime()) || (endValue.getTime() > this.activityEndDate.getTime());
    } else {
      return endValue.getTime() <= this.validateForm.controls['validity_start'].value.getTime();
    }
    // || (endValue.getTime() >= this.validateForm.controls['validity_end'].value.getTime())
    // console.log(endValue.getTime(), this.validateForm.controls['validity_start'].value.getTime(), endValue.getTime() <= this.validateForm.controls['validity_end'].value.getTime());
  };

  checkedSingle($event, data) {
    if ($event) {
      this.checked.type = this.pickType;
      this.checked.info = data;
      const listData = this.pickType + 'Data';
      this[listData].every((val, idx, array) => {
        if (val.id !== data.id) {
          val.checked = false;
        }
        return true;
      });
    } else {
      this.checked = {type: '', info: {id: ''}};
    }
  }

  pickTypeChange($event) {
    this.page = 1;
    if ($event === 'goods') {
      this.getGoodsList();
    } else {
      this.getActivityList();
    }
  }

  pageChange() {
    if (this.pickType === 'goods') {
      this.getGoodsList();
    } else {
      this.getActivityList();
    }
  }

  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    this.promoteService.getGoodsList(this.page, this.pageSize, this.searchGoodsName).subscribe(res => {
      this.loading = false;
      this.goodsData = res.data.data;
      this.total = res.data.total;
      if (!!this.goodsData.length) {
        this.goodsData.every((val, idx, array) => {
          if (this.picked.type === 'goods') {
            if (this.picked.info.id === val.id) {
              val.checked = true;
            } else {
              val.checked = false;
            }
            return true;
          } else {
            val.checked = false;
            return true;
          }
        });
      }
    });
  }

  //新建任务
  goTaskList() {
    if (this.flag) {
      this.router.navigate(['member/promote/list']);
      this.flag = false;
    }
  }

  //获取关键词列表
  getKeywordList() {
    this.promoteService.getKeywordList(1).subscribe(res => {
      if (res.code === 2000) {
        this.keywordList = res.data;
      }
    })
  }

  // 获取活动列表
  getActivityList() {
    this.loading = true;
    this.promoteService.getActivityList(this.page, this.pageSize, this.activityGoodsType, this.winnersNumber, this.searchTaskName).subscribe(res => {
      this.loading = false;
      this.activityData = res.data.data;
      this.total = res.data.total;
      if (!!this.activityData.length) {
        this.activityData.every((val, idx, array) => {
          //1 普通 2拉新 3抽奖 4团长免单
          if (val.activity_goods[0].type === 1) {
            if (val.activity_goods[0].winners_number === 0) {
              val['groupType'] = '特价团';
              console.log(val);
            } else {
              val['groupType'] = '随机免单';
            }
          } else if (val.activity_goods[0].type === 4) {
            val['groupType'] = '团长免单';
          } else if (val.activity_goods[0].type === 2) {
            val['groupType'] = '拉新团';
          } else {
            val['groupType'] = '抽奖团';
          }
          if (this.picked.type === 'activity') {
            if (this.picked.info.id === val.id) {
              val.checked = true;
            } else {
              val.checked = false;
            }
            return true;
          } else {
            val.checked = false;
            return true;
          }
        });
      }
    });
  }

  checkTag(item) {
    if (item.checked) {
      item.checked = !item.checked;
      if (this.short_name_arr.length > 0) {
        this.short_name_arr.forEach((e, i) => {
          if (e.id == item.id) {
            this.short_name_arr.splice(i, 1);
          }
        })
      } else {
        this.short_name_arr.push({id: item.id, key: item.key});
      }
      --this.num;
    } else if (!item.checked && this.num < 2) {
      item.checked = !item.checked;
      if (this.short_name_arr.length > 0) {
        let flag = false;
        this.short_name_arr.forEach((e, i) => {
          if (e.id == item.id) {
            flag = true;
          }
        });
        if (!flag) {
          this.short_name_arr.push({id: item.id, key: item.key});
        }
      } else {
        this.short_name_arr.push({id: item.id, key: item.key});
      }
      ++this.num;
    } else {
      this._message.create('error','最多选择两个关键词');
    }
    console.log(this.short_name_arr);
  }

  // 确定选择活动或商品
  confirmChecked() {
    this.goodsModalVisible = false;
    this.picked = JSON.parse(JSON.stringify(this.checked));
    if (!(this.pickType === 'goods')) {
      if (this.picked['info']['id']) {
        this.activityStartDate = new Date(this.picked['info']['start_date'] + ' 00:00:00');
        this.activityEndDate = new Date(this.picked['info']['end_date'] + ' 23:59:59');
        this.validateForm.controls['validity_start'].setValue(this.activityStartDate);
        this.validateForm.controls['validity_end'].setValue(this.activityEndDate);
      } else {
        this.validateForm.controls['validity_start'].setValue(null);
        this.validateForm.controls['validity_end'].setValue(null);
      }
    } else {
      if (this._startDate == null || this._endDate == null) {
        let start_date = new Date(moment(new Date()).format('YYYY-MM-DD HH:mm:ss'));
        let end_date = new Date(moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59');
        this.validateForm.controls['validity_start'].setValue(start_date);
        this.validateForm.controls['validity_end'].setValue(end_date);
      }
    }

    const task_content_type = (this.pickType === 'goods' ? 1 : 2);
    this.validateForm.patchValue({
      task_content_relation_id: this.checked.info.id,
      task_content_type: task_content_type
    });
  }

  // 打开弹窗
  openDialog() {
    this.goodsModalVisible = true;
    this.checked = JSON.parse(JSON.stringify(this.picked));
  }

  picError = false;//图片是否错误
  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  _handleChange(e) {

  }

  getSecCategory(level, parent_id) {
    this.firstCategory = parent_id;
    this.promoteService.getCategoryList(level, parent_id).subscribe(res => {
      if (res.code == 2000) {
        // this.secondCategory = res.data[0]['id'];
      }
    })
  }

  _value: any[] = null;

  _console(value) {
    value.length > 0 ? this.categoryError = false : this.categoryError = true;
    console.log(value);
  }

  /** load data async */
  loadData(e: { option: any, index: number, resolve: Function, reject: Function }): void {
    if (e.index === -1) {
      e.resolve(this.categories1);
      return;
    }
    let secondCategory = {};
    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      this.promoteService.getCategoryList(2, option.value).subscribe(res => {
        if (res.code == 2000) {
          let data = res.data;
          data.map((e1, i) => {
            this.secondCategory[option.label].push({
              value: e1.id,
              label: e1.category_name,
              isLeaf: true
            });
          });
          option.loading = false;
          e.resolve(this.secondCategory[option.label]);
        }
      });
    }
  }


  // 添加任务
  addTask() {
    const date = new Date(),
      now = Date.parse(date + '');
    if (this._value == null) {
      this.categoryError = true;
    } else {
      this.categoryError = false;
    }
    this.categoryTouched = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }

    if (this.validateForm.valid && !this.categoryError && now < this.validateForm.value.validity_end.getTime()) {
      this.promoteService.getInfo(this.validateForm.value.task_content_type,
        this.validateForm.value.task_content_relation_id).subscribe(res => {
        this.validateForm.value['task_content_content'] = JSON.stringify(res.data);
        this.validateForm.value.validity_start = moment(this.validateForm.value.validity_start).format('YYYY-MM-DD HH:mm:ss');
        this.validateForm.value.validity_end = moment(this.validateForm.value.validity_end).format('YYYY-MM-DD HH:mm:ss');
        this.validateForm.value['first_category'] = this._value[0];
        this.validateForm.value['second_category'] = this._value[1];
        if (this.short_name_arr.length > 0) {
          this.short_name_arr.forEach((e, i) => {
            this.validateForm.value['short_name' + (i + 1)] = e.key;
          })
        }
        this.addStatus = true;
        this.promoteService.addTask(this.validateForm.value).subscribe(rs => {
          if (rs.code === 2000) {
            this.addStatus = true;
            this._message.create('success', `任务添加成功`);
            this.router.navigate(['member/promote/list']);
          } else {
            this.addStatus = false;
            this._message.create('error', rs.data.data);
          }
        });
      });
    } else {
      console.log('error');
      // this.endDateValidators = true;
    }
  }

  changeType() {
    const type = (this.validateForm.value.type === 1 ? 2 : 1);
    if (!!this.validateForm.value.point) {
      this.validatorsPoint(this.validateForm.value.point, type);
    }
  }

  getLevel() {
    if (this.validateForm.value.point < 0 || !this.validateForm.value.point) {
      return;
    }
    this.promoteService.getLevelByPoint(this.validateForm.value.point).subscribe(res => {
      if (res.code === 2000) {
        this.level = 'lv' + res.data.id;
      } else {
        this._message.create('error', res.message);
      }
    });
  }
}
